package com.gzk.oeno.ihm;

import java.awt.GraphicsConfiguration;
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import javax.swing.JFrame;
import javax.swing.JInternalFrame;
import javax.swing.JMenuBar;

import sun.java2d.SunGraphicsEnvironment;

import com.gzk.oeno.Oenothek;
import com.gzk.oeno.dao.DBSave;
import com.gzk.oeno.ihm.menus.file.FileMenu;
import com.gzk.oeno.ihm.menus.help.HelpMenu;
import com.gzk.utils.CustomException;
import com.gzk.utils.ihm.UIUtils;
import com.gzk.utils.ihm.desktop.ConfigurableDesktopPane;
import com.gzk.utils.ihm.desktop.WindowMenu;

public class MainOenoFrame extends JFrame{

	public static MainOenoFrame INSTANCE = null;
	
	
	private final ConfigurableDesktopPane desktop = new ConfigurableDesktopPane();
	
	public MainOenoFrame(){
		super();
		this.setTitle(Oenothek.getInstance().getName() + " "+ Oenothek.getInstance().getVersion() +" (sauvegarde : "+DBSave.getFileName()+")");
		this.setSize(800, 600);
		try {
			Image image = UIUtils.loadImage(Oenothek.getInstance().getIconName());
			this.setIconImage(image);
		} catch (CustomException e){
			e.showException();
		}
		
		this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
		this.addWindowListener(new WindowAdapter() {
			public void windowClosing(WindowEvent event){
				exit();
			}
		});
		
		GraphicsConfiguration config = this.getGraphicsConfiguration(); 
		Rectangle usableBounds = SunGraphicsEnvironment.getUsableBounds(config.getDevice()); 
		this.setMaximizedBounds(new Rectangle(0, 0, usableBounds.width, usableBounds.height)); 
		this.setExtendedState(JFrame.MAXIMIZED_BOTH);
		
		
		buildFrames();
		this.setJMenuBar(buildMenuBar());
		this.setContentPane(desktop);
	}

	
	private JMenuBar buildMenuBar(){
		JMenuBar bar = new JMenuBar();
		bar.add(new FileMenu());
		bar.add(new WindowMenu(desktop, WindowMenu.FR, WindowMenu.SIZE_16));
		bar.add(new HelpMenu());
		return bar;
	}
	
	
	private void buildFrames(){
		desktop.addFrame(new HomeIFrame(), true);
	}
	

	public void addIFrame(JInternalFrame frame, boolean select){
		desktop.addFrame(frame, select);
	}

	public void exit(){
		try {
			DBSave.free();
		} catch (CustomException e) {
			e.printStackTrace();
		} finally {
			dispose();
			System.exit(0);
		}
	}
	
}
